package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-08-31
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    //=====================前台接口管理==========================
    //订单结算
    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoCheckedList = cartCheckedListResult.getData();

        if (CollectionUtils.isEmpty(cartInfoCheckedList)) {
            throw new ServiceException("请求勾选购物车商品再进行结算");
        }

        //1.准备List<OrderItem>
        List<OrderItem> orderItemList = cartInfoCheckedList.stream().map(cartInfo ->
        {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();

        //2.准备商品价格
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        String tradeNo = getTradeNo(userId);

        //3.生成交易流水号
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        return tradeVo;
    }

    //交易流水号，将来用于表单重复提交判断。即：去重处理
    private String getTradeNo(Long userId) {
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        String tradeNoKey = "user:tradeNo:" + userId;
        redisTemplate.opsForValue().set(tradeNoKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    //用户提交订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        //1.验证用户重复提交表单
        String script = "if ( redis.call('get',KEYS[1]) == ARGV[1])\n" +
                "then \n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        String tradeNoKey = "user:tradeNo:" + userId;
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), orderForm.getTradeNo());
        if (result == 0) {
            throw new ServiceException("重复提交订单");
        }

        // 2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("参数数据不合法");
        }

        // 3.校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(item -> item.getSkuId()).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();

        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        String priceResult = "";
        for (OrderItem orderItem : orderItemList) {
            BigDecimal skuPrice = orderItem.getSkuPrice();
            BigDecimal skuPriceDB = skuIdToSalePriceMap.get(orderItem.getSkuId());  //数据库最新数据
            if (skuPrice.compareTo(skuPriceDB) != 0) {
                priceResult += "商品id=[" + orderItem.getSkuId() + "]价格有变动,更新购物车价格;";
            }
        }

        if (StringUtils.isNotEmpty(priceResult)) {
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);//说明商品价格有变动，更新购物价格,抛异常,不保存订单；然后再重新结算下单。
            throw new ServiceException(priceResult);
        }

        // 4.校验库存锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();

        R<String> stringResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == stringResult.getCode()){
            throw new ServiceException(stringResult.getMsg());
        }
        String resultStr = stringResult.getData();

        //有字符串就失败，空表示成功
        if (StringUtils.hasText(resultStr)){
            throw new ServiceException(resultStr);
        }

        // 5.保存订单（订单表、订单项表、订单日志表）  保证事务特性： 原子性、一致性、隔离性、持久性
        Long orderInfoId = null;
        try {
            orderInfoId = saveOrderData(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //下单失败,解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        // 6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

        //7.发送延迟消息，取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER, MqConst.ROUTING_CANCEL_ORDER, String.valueOf(orderInfoId), MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderInfoId;
    }

    private Long saveOrderData(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        List<OrderItem> orderItemList = orderForm.getOrderItemList();

        BigDecimal totalAmount = new BigDecimal(0);
        if (StringUtils.isNotEmpty(orderItemList)) {
            for (OrderItem orderItem : orderItemList) {
                totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
            }
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(BigDecimal.valueOf(0));
        orderInfo.setOrderStatus(0);

        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        orderInfo.setCreateBy(userName);

        orderInfoMapper.insert(orderInfo);
        Long orderInfoId = orderInfo.getId();

        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfoId);
            orderItemMapper.insert(orderItem);
        }

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfoId);
        orderLog.setOperateUser("用户");
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        return orderInfoId;
    }

    //立即购买
    @Override
    public TradeVo buy(Long skuId) {
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();

        ArrayList<OrderItem> orderItemArrayList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemArrayList.add(orderItem);

        BigDecimal totalAmount = orderItem.getSkuPrice();

        Long userId = SecurityContextHolder.getUserId();
        String tradeNo = getTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemArrayList);
        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }

    //获取用户订单分页列表
    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getUserId, userId);

        if (orderStatus != null) {
            orderInfoLambdaQueryWrapper.eq(OrderInfo::getOrderStatus, orderStatus);
        }
        orderInfoLambdaQueryWrapper.orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(orderInfoLambdaQueryWrapper);

        if (StringUtils.isNotEmpty(orderInfoList)) {
            List<Long> orderInfoIdList = orderInfoList.stream().map(OrderInfo::getId).toList();
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderInfoIdList));
            Map<Long, List<OrderItem>> orderInfoIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));

            for (OrderInfo orderInfo : orderInfoList) {

                orderInfo.setOrderItemList(orderInfoIdToOrderItemListMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    //延迟关闭订单消费者
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0){
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderInfo.getOrderNo());
        }
    }

    //取消订单
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue()== 0){
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
        }
    }

    //根据订单号获取订单信息
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }
}